﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace OrderingPlatform.MvcExtension
{
    public class HttpVisitGetData
    {
        /// <summary>
        /// 获取内容
        /// </summary>
        /// <param name="strUrl"></param>
        /// <param name="strParameters"></param>
        /// <returns></returns>
        public static string GetContentBaseGet(string strUrl, string strParameters)
        {
            var gb2312 = Encoding.UTF8;//.GetEncoding("GB2312");
            var tUri = new Uri(string.Format("{0}?{1}", strUrl, strParameters));
            var tWebRequest = WebRequest.Create(tUri);
            tWebRequest.Timeout = 100000;
            tWebRequest.ContentType = "application/x-www-form-urlencoded";
            tWebRequest.Method = "GET";
            tWebRequest.UseDefaultCredentials = true;
            tWebRequest.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4");
            // tWebRequest.re.Referer = "http://www.yahoo.com/";
            var tWebResponse = tWebRequest.GetResponse();
            var strem = tWebResponse.GetResponseStream();
            if (strem != null)
                using (var tStreamReader = new StreamReader(strem, gb2312))
                {
                    var responseString = tStreamReader.ReadToEnd();
                    return responseString;
                }
            throw new Exception("不能获取Stream");
        }

        public static string GetContentBase(string strUrl, string strParameters)
        {
            var gb2312 = Encoding.GetEncoding("GB2312");
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
            var szByte = gb2312.GetBytes(strParameters);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = szByte.Length;
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4");
            httpWebRequest.Referer = "http://www.yahoo.com/";
            using (var reqStream = httpWebRequest.GetRequestStream())
            {
                reqStream.Write(szByte, 0, szByte.Length);
            }
            using (var wr = httpWebRequest.GetResponse())
            {
                //在这里对接收到的页面内容进行处理
                var responseStream = wr.GetResponseStream();
                if (responseStream != null)
                {
                    var responseReader = new StreamReader(responseStream);
                    var responseString = responseReader.ReadToEnd();
                    return responseString;
                }
                throw new Exception("不能获取Stream");
            }
        }
    }
}
